<template>
  <div class="warp_all">
    <div class="mask"></div>
    <div catchtap="null" class="warp">
      <div class="bind_item">
        <img src="../assets/icon_bindshouji.png" />
        <input placeholder="请填写您的手机号码" v-model="phoneNumber" maxlength="11" type="number" />
      </div>
      <div class="bind_item">
        <img src="../assets/icon_duanxin.png" />
        <input
          placeholder="请输入手机验证码"
          v-model="code"
          maxlength="6"
          type="number"
          bindinput="bindCode"
        />
        <div
          class="getCode getCode_default"
          style="border:1px  solid #ccc;color:#ccc"
          v-if="canClickVerifyButton"
        >{{verifyMessage}}</div>
        <div class="getCode" @click="getCode" v-else>{{verifyMessage}}</div>
      </div>
      <!-- <choose-city 
        @sendCity1='sendCity1'
        @sendCity2='sendCity2'
      ></choose-city>-->
      <div class="http">
        <img @click="isHttp" src="../assets/ic_sexEd.png" v-if="isHtpp" alt />
        <img @click="isHttp" src="../assets/ic_sex_default.png" v-else alt />
        <div>
          我已同意
          <span @click="protocol">《聊Q小屋协议》</span>
        </div>
      </div>
      <div class="sure" @click="loginBtn">登 陆</div>
      <!-- <div>{{city||'失败/测试'}}</div> -->
    </div>
  </div>
</template>
<!-- <script src="//cdn.bootcss.com/eruda/1.5.2/eruda.min.js"></script>
<script>
	eruda.init();
</script>-->
<script>
import * as API from "@/http/common/api";
import wx from "weixin-js-sdk";
import tim from "@/utils/tim";
import TIM from "tim-js-sdk";
// import AMap from "AMap";
import axios from "axios";
import Vue from "vue";
export default {
  name: "register",
  data() {
    return {
      userID:999,//测试id



      
      phoneNumber: "", //手机号
      canClickVerifyButton: true, //能发送信息状态
      verifyMessage: "获取验证码",
      isHtpp: false, //是否勾选协议
      code: null, //验证码
      longitude: 0, //经度
      latitude: 0, //纬度
      city1: "",
      city2: "",
      city: "",
      wxcode: null,
      userInfo: null,
      timer: null,
      latitude: null,
      longitude: null,
      ak: "HtQ5fGSiGEbNpI5V851CatYg4D3iHDyR",
      a:
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx554b0a1adc8cc19c&redirect_uri=http://www.xiaozounihao.club/index.html&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect"
    };
  },
  created() {},
  methods: {
    //接收城市
    sendCity1(val) {
      this.city1 = val;
    },
    sendCity2(val) {
      this.city2 = val;
    },
    // 手机号
    isLegal() {
      var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(19[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
      if (!myreg.test(this.phoneNumber)) {
        return false;
      } else {
        return true;
      }
    },
    //协议btn
    isHttp() {
      this.isHtpp = !this.isHtpp;
    },
    //协议页面
    protocol() {
      this.$localStorage.set(
        "register",
        JSON.stringify({
          inputVal: this.phoneNumber,
          code: this.code
        })
      );
      this.$router.push({ name: "Protocol", params: {} });
    },
    //获取验证码
    getCode() {
      var that = this;

      if (!this.isLegal(this.phoneNumber)) {
        this.$vux.toast.show({
          text: "手机号有误",
          type: "text"
        });
        return;
      }
      console.log(API.GET_SMS);
      this.$http(API.GET_SMS, {
        type: "GET",
        params: { mobile: this.phoneNumber }
      }).then(res => {
        console.log(res);
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "发送验证码成功",
          type: "text"
        });
        //倒计时
        var time = 60;
        (this.verifyMessage = time + "s后重新获取"),
          (this.canClickVerifyButton = true);
        that.timer = setInterval(() => {
          time--;
          if (time == 1 || time < 0) {
            that.timer && clearInterval(that.timer);
            this.verifyMessage = "重新获取验证码";
            this.canClickVerifyButton = false;
            return;
          }
          (that.verifyMessage = time + "s后重新获取"),
            (that.canClickVerifyButton = true);
        }, 1000);
      });
      that.canClickVerifyButton = true;
    },
    //第一部分
    //定位获得当前位置信息
    getMyLocation() {
      var geolocation = new qq.maps.Geolocation(
        "ACIBZ-Y2OWW-BTVRJ-OL4JL-7SDGT-5XBUN",
        "聊Q小屋"
      );
      geolocation.getIpLocation(this.showPosition, this.showErr);
      //geolocation.getLocation(this.showPosition, this.showErr);//或者用getLocation精确度比较高
    },
    showPosition(position) {
      console.log(position);
      this.city = position.city;
      this.$localStorage.set("city", position.city);
    },
    showErr(e) {
      console.log("定位失败", e);
      this.getMyLocation(); //定位失败再请求定位，测试使用
    },
    getXY() {
      this.$nextTick(res => {
        var _this = this;
        this.getMyLocation();
      });
    },
    //登陆btn
    loginBtn() {
      if (!this.isLegal(this.phoneNumber)) {
        this.$vux.toast.show({
          text: "手机号有误",
          type: "text"
        });
        return;
      }
      if (!this.code) {
        this.$vux.toast.show({
          text: "验证码有误",
          type: "text"
        });
        return;
      }
      // if (!this.city) {
      //   this.$vux.toast.show({
      //     text: "请选择城市",
      //     type: "text"
      //   });
      //   return;
      // }
      if (!this.isHtpp) {
        this.$vux.toast.show({
          text: "请勾选协议",
          type: "text"
        });
        return;
      }
      this.$http(API.LOGIN, {
        type: "POST",
        params: {
          mobile: this.phoneNumber,
          mobileCode: this.code,
          province: this.city
        }
      }).then(res => {
        if (res.data.code == 0) {
          console.log(res.data.user);
          this.userInfo = res.data.user;
          this.$localStorage.set("userInfo", JSON.stringify(res.data.user));
          this.$localStorage.set("token", res.data.token);

          this.getUserSig();
          
        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: "text"
          });
        }
      });
    },
    // registerTIM(e){

    // },
    //初始化聊天 tim
    initTIM(userSig) {
      var that = this;
      // 开始登录
      let promise = tim
        .login({
          userID: this.userInfo.userId + "",
          userSig: userSig
        })
        .then(res => {
          tim.on(TIM.EVENT.SDK_READY, function(event) {
            console.log("SDK_READY,监听==", event);
            that.$router.push({ name: "Message", params: {} });
          });
        });
      promise
        .then(function(imResponse) {
          console.log(" 登录成功=====", imResponse); // 登录成功
          
        })
        .catch(function(imError) {
          console.warn("登录 error:", imError); // 登录失败的相关信息
        });
    },
    //get腾讯 userSig
    getUserSig() {
      this.$http(API.loginTX, {
        type: "POST",
        params: {
          userId: this.userInfo.userId + ""
        }
      }).then(res => {
        this.$localStorage.set("userSig", res.data.message);
        this.initTIM(res.data.message);
      });
    },
    //验证码
    getCode() {
      var that = this;
      this.$http(API.GET_SMS, {
        type: "GET",
        params: { mobile: this.phoneNumber }
      }).then(res => {
        console.log(res);
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "发送验证码成功",
          type: "text"
        });
        //倒计时
        var time = 60;
        (this.verifyMessage = time + "s后重新获取"),
          (this.canClickVerifyButton = true);
        that.timer = setInterval(() => {
          time--;
          if (time == 1 || time < 0) {
            that.timer && clearInterval(that.timer);
            this.verifyMessage = "重新获取验证码";
            this.canClickVerifyButton = false;
            return;
          }
          (that.verifyMessage = time + "s后重新获取"),
            (that.canClickVerifyButton = true);
        }, 1000);
      });
    },
    // 截取code
    GetUrlParame(parameName) {
      /// 获取地址栏指定参数的值
      /// <param name="parameName">参数名</param>
      // 获取url中跟在问号后面的部分
      var parames = window.location.search;
      // 检测参数是否存在
      if (parames.indexOf(parameName) > -1) {
        var parameValue = "";
        parameValue = parames.substring(
          parames.indexOf(parameName),
          parames.length
        );
        // 检测后面是否还有参数
        if (parameValue.indexOf("&") > -1) {
          // 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
          parameValue = parameValue.substring(0, parameValue.indexOf("&"));
          // 去掉参数名, 得到最终纯值字符串
          parameValue = parameValue.replace(parameName + "=", "");
          return parameValue;
        }
        return "";
      }
    },
    // getOpenId
    getOpenId(code) {
      this.$http(API.getOpenId, {
        type: "POST",
        params: { code: code }
      }).then(res => {
        if (res.data.code == 0) {
          console.log("openId==========", res.data.openId);
          this.$localStorage.set("openId", res.data.openId);
        } else {
          this.$vux.toast.show({
            text: res.data.msg,
            type: "text"
          });
        }
      });
    },
    getWxCity(lat, lng) {
      var that = this;
      this.$http(API.dizhi, {
        type: "POST",
        params: {
          lat: lat + "",
          lng: lng + ""
        }
      }).then(res => {
        if (res.data.code == 0) {
          that.city = res.data.message.city;
          that.$localStorage.set("city", res.data.message.city);
        } else {
          this.$vux.toast.show({
            text: res.data.msg,
            type: "text"
          });
        }
      });
    },
  },
  watch: {
    phoneNumber(newVal, oldVal) {
      if (!newVal) return;
      if (newVal.length == 11) {
        this.canClickVerifyButton = false;
      } else {
        this.canClickVerifyButton = true;
      }
    },
    city1(newVal, oldVal) {
      console.log(newVal);
      if (newVal.indexOf("市") > -1) {
        this.city = newVal;
      }
    },
    city2(newVal, oldVal) {
      if (newVal.indexOf("市") > -1) {
        this.city = newVal;
      }
    }
  },
  mounted() {
    // this.first()
    var that = this;
    this.$http(API.getShareData, {
      type: "GET",
      params: {
        url: "http://www.xiaozounihao.club/index.html"
      }
    }).then(res => {
      console.log(res);
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: "wx554b0a1adc8cc19c", // 必填，公众号的唯一标识
        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
        signature: res.data.signature, // 必填，签名，见附录1
        jsApiList: ["getLocation"]
      });
      var that = this;
      wx.ready(function(res) {
        wx.getLocation({
          type: "gcj02",
          success: function(res) {
            console.log("位置++++", res);
            this.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            this.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
            that.getWxCity(res.latitude, res.longitude);
          },
          cancel: function(res) {
            console.log("查看附件机器，首先要授权位置信息", res);
          },
          fail: function(res) {
            console.info("ready getLocation fail=" + JSON.stringify(res));
          }
        });
      });
    });
    if (this.$localStorage.get("openId")) return;
    var code = this.GetUrlParame("code");
    if (code) {
      console.log("code:", code);
      this.getOpenId(code); //换区openId
    } else {
      //授权页面
      window.location.href = this.a; //是否                                微信授权
    }
    if (this.$localStorage.get("register")) {
      var registerData = JSON.parse(this.$localStorage.get("register"));
      this.phoneNumber = registerData.inputVal;
      this.code = registerData.code;
    }
  },

  components: {  }
};
</script>
<style scoped >
html {
}
body {
  background: #fff !important;
}
.http {
  display: flex;
  margin-top: 10px;
  align-items: center;
  font-size: 12px;
}
.http > img {
  width: 16px;
  height: 16px;
  margin-right: 8.5px;
}
.mask {
  position: fixed;
  left: 0px;
  top: 0;
  width: 100%;
  height: 100%;
  background: #fff;
}
.warp_all {
  width: 100%;
  height: 100%;
  background: #fff !important;
}
#app {
  width: 100%;
  height: 100%;
}
.head {
  width: 50px;
  height: 50px;
  margin: 0 auto;
  padding-top: 30px;
  margin-bottom: 30px;
}
.warp {
  background: #fff;
  border-radius: 5px;
  margin: 0 auto;
  width: 319px;
  height: 267px;
  box-sizing: border-box;
  position: relative;
  padding-top: 50px;
}
.bindTitle {
  text-align: center;
  line-height: 60px;
  font-size: 16px;
}
.bind_item {
  display: flex;
  align-items: center;
  height: 60px;
  border-bottom: 1px solid #f2f2f2;
}
.bind_item > img {
  width: 28px;
  height: 28px;
  margin-right: 15px;
}
.bind_item > input {
  border: none;
  background: #fff;
  width: 130px;
  flex: 1;
}
.getCode {
  text-align: center;
  border-radius: 13px;
  background: #e83263;
  color: #fff;
  font-size: 13px;
  padding: 4px 8.5px;
}
.getCode_default {
  border: #e83263;
  background: #fff;
}
.sure {
  width: 279px;
  height: 40px;
  margin: 0 auto;
  background: #e83263;
  text-align: center;
  color: #fff;
  line-height: 40px;
  font-size: 16px;
  border-radius: 20px;
  margin-top: 80px;
}
.vipMessage_warp {
  display: flex;
  align-items: center;
  margin-top: 8px;
}
.vipMessage_warp > img {
  width: 18px;
  height: 18px;
  margin-right: 4px;
}
.vipMessage_log {
  width: 43px;
  height: 14px;
  line-height: 14px;
  color: #fff;
  background: #e9a2b8;
  border-radius: 7px;
  text-align: center;
  font-size: 8px;
  margin-right: 10px;
}
.vipMessage_number {
  display: flex;
  align-items: center;
  color: #e9a2b8;
  font-size: 11px;
}
.num_log {
  font-size: 8px;
  margin-left: 11px;
  height: 12px;
  line-height: 12px;
  color: #fff;
  text-align: center;
  width: 32px;
  background: #e9a2b8;
  border-radius: 1px;
}
.precent {
  position: relative;
  overflow: hidden;
  border-radius: 2px;
  margin-top: 2px;
}
.precent_bg {
  width: 94px;
  height: 3px;
  background: #e9a2b8;
}
.precent_plan {
  background: #fff;
  height: 3px;
  left: 0;
  top: 0;
  position: absolute;
}
.ifRegister {
  text-align: center;
  margin-top: 18px;
  color: #666;
}
.ifRegister > span {
  color: #333;
}
.warp_all input {
  font-size: 14px;
}

.chooseCityBox {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.box {
  width: 500px;
  height: 600px;
  box-sizing: border-box;
  padding-top: 50px;
  box-shadow: #ccc 0px 0px 50px 2px;
}
</style>
